<?php

namespace app\admin\controller\serial;

use app\common\controller\Backend;
use app\common\controller\Api;
use EasyWeChat\Factory;
use PHPExcel;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use think\Db;
use PHPExcel_IOFactory;
/**
 * 专属账号
 *
 * @icon fa fa-circle-o
 */
class Special extends Backend
{
    protected $searchFields = 'id,code';
    /**
     * Special模型对象
     * @var \app\admin\model\serial\Special
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\serial\Special;
        $this->modelLog = new \app\admin\model\serial\SpecialLog;
       $this->view->assign("getCancelList", $this->model->getCancelList());
       $this->view->assign("getUseList", $this->model->getUseList());
       $this->view->assign("getSendList", $this->model->getSendList());
       $this->view->assign("getTypepdfList", $this->model->getTypepdfList());
  
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','userid','code','is_send','type_pdf','is_cancel','is_use','createtime','updatetime','usetime','publish']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->where(['id'=>$ids])->find();
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params['z_publish']    = \think\Session::get('admin')['userid'];
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {

                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
     //产品调货
    public function send(){
        if($this->request->isAjax()){
            //接收序列号
            $row = $this->request->request('row/a');
            //封装数组
            $codeListArr = explode("\n", $row['code']);
            //去除空数组
            $codeListArr = array_filter($codeListArr);
            if (!$codeListArr) $this->error('请输入专属号信息');
            //开启事务
            Db::startTrans();
            foreach ($codeListArr as $v) {
                //去除符号和空格
                $v = str_replace("-", "", str_replace(" ", '', trim($v)));
                $codeArr = $this->model->where(['code' => $v])->find();
                if (!$codeArr) $this->error('专属号不存在' . $v);
                if ($codeArr['is_cancel'] == 2) $this->error('专属号已作废:' . $v);
                $data['is_send'] = 2;
                $send_show = $this->model->where(['code' => $v])->update($data);
                if (!$send_show) {
                    Db::rollback();
                    $this->error('发送失败');
                }
            }
            // 提交事务
            Db::commit();
            $this->success('发送成功' . count($codeListArr) . '个');

        }
        return $this->view->fetch();
    }

    
    //产品作废调整
    public function cancel()
    {
        if($this->request->isAjax()){
            //接收序列号
            $row = $this->request->request('row/a');
            //封装数组
            $codeListArr = explode("\n", $row['code']);
            //去除空数组
            $codeListArr = array_filter($codeListArr);
            if (!$codeListArr) $this->error('请输入序列号信息');
            //开启事务
            Db::startTrans();
            foreach ($codeListArr as $v) {
                //去除符号和空格
                $v = str_replace("-", "", str_replace(" ", '', trim($v)));
                $codeArr = $this->model->where(['code' => $v])->find();
                if (!$codeArr) $this->error('专属号不存在' . $v);
                if ($codeArr['is_cancel'] == 2) $this->error('专属号已作废:' . $v);
                if ($codeArr['is_use'] == 2) $this->error('专属号已被用户使用:' . $v);
                if ($codeArr['is_send'] != 2) $this->error('专属号未发送:' . $v);
                $data['is_cancel'] = 2;
                $send_show = $this->model->where(['code' => $v])->update($data);
                if (!$send_show) {
                    Db::rollback();
                    $this->error('专属号作废失败');
                }
            }
            // 提交事务
            Db::commit();
            $this->success('专属号作废成功' . count($codeListArr) . '个');

        }
        return $this->view->fetch();
    }
    
    public function generate()
    {
        if($this->request->isAjax())
        {
            $row = $this->request->request('row/a');
           
            if($row['action'] == 2 && !$row['userid'])
            {
                $this->error('请选择企业微信收取人');
            }
            if($row['number'] < 1 || !$row['number'] || $row['number'] > 100000)
            {
                $this->error('请填写大于0的数量,或数量不要大于10万');
            }
      
            $data = [];
            for ($i=1;$i<=$row['number'];$i++)
            {
                $data[$i] = [
                    'code'=>$this->random(6),
                    'publish'=>\think\Session::get('admin')['userid'],
                    'z_publish'=>\think\Session::get('admin')['userid'],
                ];
            }
            // 启动事务
            Db::startTrans();
            try{
              $this->model->saveAll($data);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('数据重复。','',$e->getMessage());
            }
            $url = '';
            $res = false;
            //下载到本地
            if($row['action'] == 1)
            {
                $url = $this->export($data,'',5000,$name = '专属账号');
            }else{
                $this->export($data,$row['userid'],5000,$name = '专属账号');
            }
            // 提交事务
            Db::commit();
            $this->success('序列号生成成功！',$url);

        }
        return $this->view->fetch();
    }

    public function export(array $list,$userid = null,$limit=1000,$name='')
    {
        $objPHPExcel = new PHPExcel();
        $count = ceil(count($list) / $limit);
        $row = $objPHPExcel->setactivesheetindex(0);
        //列为文本
        $row->getStyle('A')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        for ($i=1;$i<=$count;$i++){
            $row->setTitle("$i");
            $offset = ($i-1)*(10);
            $array = array_slice($list,$offset,$limit);
            foreach ($array as $k => $v) {
                $newkeyStr= substr($v['code'], 0, 3);
                $newkey= $newkeyStr . '- ' . substr($v['code'], 3, 5);
                $row->setcellvalue('A'.($k+1), ''.$newkey.'');
                unset($newkeyStr,$newkey);
                $row->getColumnDimension('A')->setWidth(30);
            }
            if($i <= $count-1)
            {
                //创建一个新的工作空间(sheet)
                $objPHPExcel->createSheet();
                $row = $objPHPExcel->setactivesheetindex($i);
                $row->setTitle("$i");
                //列为文本
                $row->getStyle('A')->getNumberFormat()
                    ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
            }
        }
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $date = date('Y-m-d H:i:s',time());
        $filename = $this->auth->username.'-'.$name.'-'.$date.'.xlsx';
        $objWriter->save('./special/xlsx/'.$filename);
        //添加操作日志
        $data = [
            'text' => $this->auth->username.'生成'.$name.'/'.count($list).'个',
            'url' => '/special/xlsx/'.$filename,
        ];
        //上传到企业微信临时文件
        if($userid)
        {
            $Api = new Api();
            $config = $Api->getConfig($Api->getDefault('Assistant'));
            $app = Factory::work($config);
            $path = ROOT_PATH . 'public/special/xlsx/'.$filename;
            $res = $app->media->uploadFile($path);
            //发送文件给操作人
            if($res['errcode'] == 0 ){
                $data['media_id'] = $res['media_id'];
                $data['text'] .='发送给'.$this->auth->username;
                $response = pushMsgText($config,'file',['media_id'=>$res['media_id']] ,$userid);
               if($response['err_msg'] != 'ok'){
                    return false;
                }
           
            }
            $log = $this->modelLog->create($data);
            return $log->id;
        }
        $log = $this->modelLog->create($data);
        return $data['url'];
    }
    
    /**
     * 生产序列号
     * @param $length
     * @param string $chars
     * @return string
     */
    public function random($length, $chars = '01234567893216549870') {
        $hash = '';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }
}
